<?php

namespace App\Http\Controllers\Area;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Divide\CitySplitRatio;
use App\Models\Divide\PersonSplitRatio;
use Illuminate\Http\Request;

class CityController extends Controller
{
    //
    use ResponseData;
    public function getCitys(CitySplitRatio $model,Request $request){

        $model = $model->select('category_id','ratio_id','city_name','pid','area_code','ratio','level');
        $model = $model->withCount('children');
        $model = $model->where('category_id',$request->category_id);
        if($request->filled('pid')){
            $model = $model->where('pid',$request->pid);
        }else{
            $model = $model->where('pid',0);
        }
        if($request->filled('level')){
            $model->where('level',$request->level);
        }

        $model = $model->get();
        $res = $model->transform(function ($city) {
            $city->hasChildren = $city->children_count;
            unset($city->children_count);
            return $city;
        });

        return $this->success($res);
    }
    public function updateCityRatio(CitySplitRatio $model,Request $request){
        $data = $model->query()->find($request->ratio_id);
        if($data){
            $data->ratio = $request->ratio;
            $data->save();
        }
        return $this->success('更新成功');
    }
    public function batchUpdate(CitySplitRatio $model,Request $request){
        if($request->filled('province_ratio')){
            $level = 1;
            $ratio = $request->province_ratio;
            $this->updateRatio($request->category_id,$level,$ratio);
        }
        if($request->filled('city_ratio')){
            $level = 2;
            $ratio = $request->city_ratio;
            $this->updateRatio($request->category_id,$level,$ratio);
        }
        if($request->filled('district_ratio')){
            $level = 3;
            $ratio = $request->district_ratio;
            $this->updateRatio($request->category_id,$level,$ratio);
        }

        return $this->success('更新成功');
    }
    protected function updateRatio($category_id,$level,$ratio){
        CitySplitRatio::query()
            ->where('category_id',$category_id)
                ->where('level',$level)
                ->update(['ratio'=>$ratio]);
    }
}
